//
//  WKAnimatorManager.m
//  WK天气
//
//  Created by qitian on 16/6/29.
//  Copyright © 2016年 王琨. All rights reserved.
//

#import "WKAnimatorManager.h"
#import "WKCircleSpreadAnimator.h"
#import "WKExpandAnimator.h"
#import "UIViewController+WKRefrer.h"

typedef NS_ENUM(NSInteger, WKAnimatorStyle)
{
    WKAnimatorStyle_CircleSpread,
    WKAnimatorStyle_Expand,
    WKAnimatorStyle_None
};


@interface WKAnimatorManager ()

@property (nonatomic, assign) WKAnimatorStyle style;
@property (nonatomic, strong) UIPercentDrivenInteractiveTransition *percentDrivenTransition;
@property (nonatomic, strong) UIScreenEdgePanGestureRecognizer * edgePan;
@property (nonatomic, strong) UINavigationController * edgePanVC;
@end

@implementation WKAnimatorManager

+ (instancetype)sharedAnimatorManager
{
    static WKAnimatorManager * m = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        m = [WKAnimatorManager new];
    });
    return m;
}

- (void)setAnimator:(WKBaseAnimator *)animator
{
    _animator = animator;
    _style = animator == nil ? WKAnimatorStyle_None : ([animator isKindOfClass:[WKExpandAnimator class]] ? WKAnimatorStyle_Expand : WKAnimatorStyle_CircleSpread);
}
#pragma mark 模态推送代理
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
                                                                  presentingController:(UIViewController *)presenting
                                                                      sourceController:(UIViewController *)source {
    // 推出控制器的动画
    if (self.animator) {
        self.animator.type = YES;
    }
    return self.animator;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    // 退出控制器动画
    if (self.animator) {
        self.animator.type = NO;
    }
    return self.animator;
}

#pragma mark 导航栏推送代理
- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                  animationControllerForOperation:(UINavigationControllerOperation)operation
                                               fromViewController:(UIViewController*)fromVC
                                                 toViewController:(UIViewController*)toVC
{
    
    if (self.animator) {
        self.animator.type = UINavigationControllerOperationPush == operation;
    }
    
    if (operation == UINavigationControllerOperationPush) {
        if (toVC.refererStr.length <=0 ) {
            if ([fromVC isKindOfClass:[UITabBarController class]]) {
                fromVC = ((UITabBarController *)fromVC).selectedViewController;
            }
            while ([fromVC respondsToSelector:@selector(currentViewController)]) {
//                fromVC = [(id)fromVC currentViewController];
                fromVC = [fromVC performSelector:@selector(currentViewController)];
            }
            toVC.refererStr = fromVC.refererStr;
        }
    }
    
    BOOL flag = NO;// self.style == WKAnimatorStyle_Expand && operation == UINavigationControllerOperationPop;
    return flag ? nil : self.animator;
}

////下面这一圈都没用上 原因未知，需要调用使用··
- (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController
{
    if ([animationController isKindOfClass:[WKBaseAnimator class]])
    {
        WKBaseAnimator * baseA = (WKBaseAnimator *)animationController;

        if (baseA.type) {//pop
            self.edgePanVC = navigationController;
            if (_edgePan.view) {
                [_edgePan.view removeGestureRecognizer:_edgePan];
            }
            if (baseA.edgeType != UIRectEdgeNone){
                self.edgePan.edges = baseA.edgeType;
                [self.edgePanVC.view addGestureRecognizer:self.edgePan];
            }
        }
        else
        {
            if (baseA.edgeType == UIRectEdgeNone)
            {
                return nil;
            }
            return self.percentDrivenTransition;
        }
    }
    
    return nil;
}


//- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
//{
//    
//    id<UIViewControllerTransitionCoordinator> tc = navigationController.topViewController.transitionCoordinator;
//
//    if (@available(iOS 10.0, *)) {
//        //针对交互动画，如果从侧滑状态到停止侧滑状态会调用，但是从未侧滑状态到侧滑状态是否也会调用？？ 如何区分？
//        [tc notifyWhenInteractionChangesUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
////            DLog(@"------------------");
////            DLog(@"Animated = %ld",context.isAnimated);
////            DLog(@"Interactive = %ld",context.isInteractive);
////            DLog(@"Cancelled = %ld",context.isCancelled);
////            DLog(@"Interruptible = %ld",context.isInterruptible);
////            DLog(@"------------------");
//            //此时动画状态永远为1，交互结束时，还是回收动画过程,考虑延时？ 有无必要？
////            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                if (context.isCancelled || !context.isInteractive) {
//                    if (self.willShowBlock) {
//                        self.willShowBlock();
//                    }
//                }
////            });
//
//        }];
//    }
//    else
//    {
//        [tc notifyWhenInteractionEndsUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
//            if (self.willShowBlock) {
//                self.willShowBlock();
//            }
//        }];
//    }
//
//}
//
//- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
//{
//    if (self.didShowBlock) {
//        self.didShowBlock();
//    }
//}


#pragma mark getter/setter
- (UIScreenEdgePanGestureRecognizer *)edgePan
{
    if (!_edgePan) {
        _edgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(edgePanGesture:)];
    }
    return _edgePan;
}

- (void)edgePanGesture:(UIScreenEdgePanGestureRecognizer *)pan
{
    CGFloat progress = [pan translationInView:self.edgePanVC.view].x / self.edgePanVC.view.bounds.size.width;
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {
            self.percentDrivenTransition = [UIPercentDrivenInteractiveTransition new];
            [self.edgePanVC popViewControllerAnimated:YES];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [self.percentDrivenTransition updateInteractiveTransition:progress];
        }
            break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:
        {
            if (progress > 0.5) {
                [self.percentDrivenTransition finishInteractiveTransition];
                if (self.edgePan.view) {
                    [self.edgePan.view removeGestureRecognizer:self.edgePan];
                }
            }
            else
            {
                [self.percentDrivenTransition cancelInteractiveTransition];
            }
            self.percentDrivenTransition = nil;
        }
        default:
            break;
    }
}

@end
